package com.softserveinc.ita.kaiji.multiplay.websocket.controller;

import com.softserveinc.ita.kaiji.multiplay.dto.client.DtoClient;
import com.softserveinc.ita.kaiji.multiplay.service.PlayerService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.stereotype.Controller;

import java.security.Principal;

/**
 * Project kaiji-game
 * Created by mikeldpl
 * 22.03.2015 13:19.
 */
@Controller("SocketGameController")
public class SocketGameController {

	private static final Logger LOG = Logger.getLogger(SocketGameController.class);

	@Autowired
	public PlayerService playerService;

	@MessageMapping("/queue/game/ship")
	public void inComeMessageHandler(Principal principal
			, @Header(value = "simpSessionId") String simpSessionId
			, @Payload DtoClient msg) {
		if (LOG.isInfoEnabled()) {
			LOG.info("----> Send message " + msg + " user " + principal.getName() + " session " + simpSessionId);
		}
		playerService.inComeMessage(principal, simpSessionId, msg);
	}

//	@Autowired
//	public SimpMessagingTemplate template;

	@SubscribeMapping("/user/queue/game/{shipName}")
	public void connectHandler(Principal principal,
							   @Header(value = "simpSessionId") String simpSessionId,
							   @DestinationVariable("shipName") String shipName) {
		if (LOG.isInfoEnabled()) {
			LOG.info("----* Connect user " + principal.getName() + " to " + shipName + " session " + simpSessionId);
		}
		playerService.addPlayer(principal, simpSessionId, shipName);
	}


	public void disconnectHandler(String simpSessionId) {
		if (LOG.isInfoEnabled()) {
			LOG.info("----x Disconnect session " + simpSessionId);
		}
		playerService.remove(simpSessionId);
	}
}
